<script setup>
import {
    Plus
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import COS from 'cos-js-sdk-v5';
import { addBanner, updateBanner } from '@/apis/content';
import { ElMessage } from 'element-plus';
const centerDialogVisible = ref(false)
const formRef = ref()
const formModel = ref({
    id: '',
    content: '',
    imgUrl: '',
    hrefUrl: ''
})
const rules = {
    content: [{ required: true, message: '请输入描述', trigger: 'blur' }, {
        pattern: /^\S{1,10}$/, message: '请输入1-10个字符', trigger: 'blur'
    }],
    imgUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }],
    hrefUrl: [{ required: true, message: '请输入/category/开头的地址', trigger: 'blur' },
    {
        // eslint-disable-next-line no-useless-escape
        pattern: '^\/category\/[0-9]{7}$', message: '请输入正确的跳转地址', trigger: 'blur'
    }]
}

// 图片上传
const beforeAvatarUpload = (file) => {
    const isJPG = ['image/jpeg', 'image/png', 'image/bmp'].includes(file.type)
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isJPG) {
        ElMessage.error(new Error('请上传JPG或PNG格式的图片!'));
        return false
    }
    if (!isLt5M) {
        ElMessage.error(new Error('图片大小不能超过5M!'));
        return false
    }
    return true
}
const uploadImage = (params) => {
    // console.log(params.file);
    const cos = new COS({
        SecretId: 'AKIDXvBFBwTionfKlxzmLfolTwA9pHUYO0fD',
        SecretKey: 'VqGsPnz29B4pbIvfGpIdmmomaP2Vozyp'
    })
    cos.putObject({
        Bucket: 'dnyx-1326918032',
        Region: 'ap-chengdu',
        Key: params.file.name,
        StorageClass: 'STANDARD',
        Body: params.file,
    }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
            formModel.value.imgUrl = 'http://' + data.Location;
        } else {
            ElMessage.error(new Error('图片上传失败!'));
        }
    })
}

// 提交表单
const emit = defineEmits(['success'])
const onSubmit = async () => {
    await formRef.value.validate()
    const idEdit = formModel.value.id
    if (idEdit) {
        await updateBanner(formModel.value)
        setTimeout(() => {
            ElMessage.success('修改成功!');
        }, 300)
    } else {
        await addBanner(formModel.value)
        setTimeout(() => {
            ElMessage.success('添加成功!');
        }, 300)
    }
    centerDialogVisible.value = false;
    emit('success')
}

// 组件对外暴露方法  open   基于open传来的参数,区分是添加还是编辑
// open({}) => 表单无需渲染  open({id:1}...) => 渲染表单
// open调用后, 打开弹窗
const open = (row) => {
    // console.log(row);
    formModel.value = { ...row }
    centerDialogVisible.value = true;
}
// 组件对外暴露方法  close   关闭弹窗
defineExpose({
    open
})
</script>

<template>
    <el-dialog v-model="centerDialogVisible" :title="formModel.id ? '编辑' : '添加'" width="500" center>
        <el-form :model="formModel" :rules="rules" ref="formRef" label-width="70px" style="padding-right: 30px;">
            <el-form-item label="ID" v-show="formModel.id">
                <el-input v-model="formModel.id" disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="content">
                <el-input v-model="formModel.content" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="路径" prop="hrefUrl">
                <el-input v-model="formModel.hrefUrl" placeholder="请输入/category/{id}开头的地址"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="imgUrl">
                <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadImage"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="formModel.imgUrl" :src="formModel.imgUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="onSubmit">确定</el-button>
                <el-button @click="centerDialogVisible = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
    width: 215px;
    height: 120px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>